package com.alumni_circle.core.security;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.alumni_circle.core.config.RedisCache;
import com.alumni_circle.core.entity.ResponseModel;
import com.alumni_circle.core.utils.JwtUtils;
import com.alumni_circle.core.utils.SecurityUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 龙小虬
 * @since 2020-08-01 12:49
 *
 * 用户登录成功返回类
 */
@Component
public class SuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {

        System.out.println(("登录成功"));
        String key = IdUtil.simpleUUID();

        //获取相应的bean
        BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(httpServletRequest.getServletContext());
        RedisCache redisCache = (RedisCache) factory.getBean("redisCache");
        JwtUtils jwtUtils = (JwtUtils)factory.getBean("jwtUtils");

        //将登录用户的数据存入redis
        redisCache.setCacheObject(key, SecurityUtils.getLoginUser());
        //进行JWT加密
        String token = jwtUtils.encryption(key,SecurityUtils.getRole());
        Map<String,String> result = new HashMap<>();
        result.put("role",SecurityUtils.getRole());
        result.put("token",token);
        //设置信息头
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter printWriter = httpServletResponse.getWriter();
        ResponseModel responseModel = new ResponseModel<>(result);
        //信息更改为json格式
        JSON json = JSONUtil.parse(responseModel);
        //写入数据
        printWriter.write(json.toString());
    }
}
